<template>
  <div class="order-page">
    <div class="order-container">
      <!-- 左侧购物车 -->
      <div class="cart-panel">
        <div class="cart-header">
          <h3>当前订单</h3>
          <el-button type="text" @click="clearCart">清空</el-button>
        </div>

        <div class="cart-items">
          <div v-if="cartItems.length === 0" class="empty-cart">
            <el-icon size="48">
              <ShoppingCart/>
            </el-icon>
            <p>购物车为空</p>
          </div>

          <div v-else class="cart-item-list">
            <div v-for="item in cartItems" :key="item.dishId" class="cart-item">
              <div class="item-image">
                <img :src="item.photo" :alt="item.name"/>
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-spec">{{ item.uname }}</div>
                <div class="item-price">¥{{ item.basePrice }}</div>
              </div>
              <div class="item-actions">
                <el-button size="small" @click="removeFromCart(item.dishId)">
                  <el-icon>
                    <Close/>
                  </el-icon>
                </el-button>
                <div class="quantity-controls">
                  <el-button size="small" @click="decreaseQuantity(item.dishId)">-</el-button>
                  <span class="quantity">{{ item.quantity }}</span>
                  <el-button size="small" @click="increaseQuantity(item.dishId)">+</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="cart-footer">
          <div class="cart-total">
            <span>合计: {{ totalItems }}份</span>
            <span class="total-price">¥{{ totalPrice }}</span>
          </div>
          <div class="cart-actions">
            <el-button type="warning" @click="clearCart">清空</el-button>
            <!--            <el-button type="primary" @click="submitOrder" :disabled="cartItems.length === 0">-->
            <!--              下单 ({{ totalItems }})-->
            <!--            </el-button>-->
            <el-button type="success" @click="submitOrder" :disabled="cartItems.length === 0">
              下单 ({{ totalItems }}份) - ¥{{ totalPrice }}
            </el-button>
          </div>
        </div>
      </div>


           <!-- 右侧菜品选择 -->
      <div class="menu-panel">
        <!-- 分类标签 -->
        <div class="category-tabs">
          <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
            <el-tab-pane
                v-for="category in categories"
                :key="category.categoryId"
                :label="category.categoryName"
                :name="category.categoryId"
            />
          </el-tabs>
        </div>



        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input
              v-model="searchKeyword"
              placeholder="请输入你要搜索的商品"
              prefix-icon="Search"
              clearable
              @input="handleSearch"
          />
        </div>

               <!-- 菜品网格 -->
        <div class="dish-grid">
          <div
              v-for="dish in filteredDishes"
              :key="dish.dishId"
              class="dish-card"
              :class="{ 'sold-out': dish.isOnSale == true }"
              @click="addToCart(dish)"
          >
            <div class="dish-image">
              <img :src="dish.photo" :alt="dish.name"/>
              <div v-if="dish.isOnSale == false" class="sold-out-overlay">
                停售
              </div>
              <div v-if="dish.discount" class="discount-badge">
                {{ dish.discount }}
              </div>
            </div>
            <div class="dish-info">
              <h4 class="dish-name">{{ dish.name }}</h4>
              <p class="dish-desc">{{ dish.uname }}</p>
              <div class="dish-price">¥{{ dish.basePrice }}</div>
            </div>
          </div>
        </div>


        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="totalDishes"
              :page-sizes="[12, 24, 36, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <!--    <div class="bottom-actions">-->
    <!--      <div class="action-left">-->
    <!--        <el-button type="warning" @click="clearCart">清空</el-button>-->
    <!--        <el-button type="warning" @click="showPickupOrders">-->
    <!--          取单 <el-badge :value="pendingOrders" class="badge" />-->
    <!--        </el-button>-->
    <!--      </div>-->

    <!--      <div class="action-center">-->
    <!--        <el-button type="success" size="large" @click="submitOrder" :disabled="cartItems.length === 0">-->
    <!--          下单 ({{ totalItems }}份) - ¥{{ totalPrice }}-->
    <!--        </el-button>-->
    <!--      </div>-->

    <!--      <div class="action-right">-->
    <!--        <el-button type="warning" @click="addSpicy">加辣</el-button>-->
    <!--        <el-button type="warning" @click="addNumb">微麻</el-button>-->
    <!--        <el-button type="warning" @click="noSpicy">不辣</el-button>-->
    <!--        <el-button type="info" @click="takeaway">打包</el-button>-->
    <!--        <el-button type="primary" @click="makeReservation">预约</el-button>-->
    <!--      </div>-->
    <!--    </div>-->
  </div>

  <!-- 下单确认对话框 -->
  <el-dialog
      v-model="orderDialogVisible"
      title="选择桌号"
      width="500px"
      :before-close="closeOrderDialog"
  >
    <div class="table-selection">
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="人数" prop="peopleCount">
          <el-input-number
              v-model="orderForm.peopleCount"
              :min="1"
              :max="20"
              placeholder="请输入用餐人数"
          />
        </el-form-item>

        <el-form-item label="桌位区域" prop="tableZone">
          <el-select v-model="orderForm.tableZone" placeholder="请选择桌位区域" style="width: 100%">
            <el-option label="A区" value="A"/>
            <el-option label="B区" value="B"/>
            <el-option label="C区" value="C"/>
            <el-option label="D区" value="D"/>
            <el-option label="E区" value="E"/>
            <el-option label="F区" value="F"/>
          </el-select>
        </el-form-item>

        <el-form-item label="桌号" prop="tableNumber">
          <el-select
              v-model="orderForm.tableNumber"
              placeholder="请选择桌号"
              style="width: 100%"
              :disabled="!orderForm.tableZone"
          >
            <el-option
                v-for="table in availableTables"
                :key="table.number"
                :label="`${table.number} (${table.capacity}人桌)`"
                :value="table.number"
                :disabled="table.status !== 'available'"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="口味偏好">
          <el-radio-group v-model="orderForm.tastePreference">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="spicy">加辣</el-radio>
            <el-radio label="numb">微麻</el-radio>
            <el-radio label="no-spicy">不辣</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="打包方式">
          <el-radio-group v-model="orderForm.packaging">
            <el-radio label="dine-in">堂食</el-radio>
            <el-radio label="takeaway">打包</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
              v-model="orderForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入特殊要求或备注信息"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeOrderDialog">取消</el-button>
        <el-button type="primary" @click="confirmOrder" :loading="orderSubmitting">
          确认下单
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, computed, onMounted, reactive} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import axios from 'axios'
import {Close} from "@element-plus/icons-vue";

const router = useRouter()

// 响应式数据
const activeCategory = ref('all')
const searchKeyword = ref()
const currentPage = ref(1)
const pageSize = ref(12)
const cartItems = ref([])
const pendingOrders = ref(2)

// 订单对话框相关
const orderDialogVisible = ref(false)
const orderSubmitting = ref(false)
const orderForm = reactive({
  tastePreference: 'normal',
  packaging: 'dine-in',
  remark: '',
  peopleCount: 1,
  tableZone: '',
  tableNumber: ''
})

// 桌位数据
const tables = ref([
  {id: 1, number: 'A01', capacity: 4, status: 'available', zone: 'A'},
  {id: 2, number: 'A02', capacity: 6, status: 'occupied', zone: 'A'},
  {id: 3, number: 'A03', capacity: 2, status: 'available', zone: 'A'},
  {id: 4, number: 'A04', capacity: 8, status: 'available', zone: 'A'},
  {id: 5, number: 'A05', capacity: 4, status: 'available', zone: 'A'},
  {id: 6, number: 'A06', capacity: 6, status: 'available', zone: 'A'},
  {id: 7, number: 'B01', capacity: 4, status: 'available', zone: 'B'},
  {id: 8, number: 'B02', capacity: 6, status: 'occupied', zone: 'B'},
  {id: 9, number: 'C01', capacity: 2, status: 'available', zone: 'C'},
  {id: 10, number: 'D01', capacity: 8, status: 'available', zone: 'D'},
  {id: 11, number: 'E01', capacity: 4, status: 'available', zone: 'E'},
  {id: 12, number: 'F01', capacity: 6, status: 'available', zone: 'F'}
])


// 分类数据
const categories = ref([
  { categoryName: '全部', categoryId: 'all' },
  { categoryName: '热菜', categoryId: 'hot' },
  { categoryName: '凉菜', categoryId: 'cold' },
  { categoryName: '汤羹', categoryId: 'soup' },
  { categoryName: '主食', categoryId: 'staple' },
  { categoryName: '海鲜', categoryId: 'seafood' }
])


// 可用桌位计算属性
const availableTables = computed(() => {
  if (!orderForm.tableZone) return []
  return tables.value.filter(table =>
      table.zone === orderForm.tableZone &&
      table.status === 'available' &&
      table.capacity >= orderForm.peopleCount
  )
})

// 菜品数据
const dishes = ref([])


// 查询
function findPage() {
  axios({
    url: '/api/dishManagement/listDishManagement',
    method: 'post',
    data: {
      current: currentPage.value,
      size: pageSize.value,
      code: searchKeyword.value,
    }
  }).then(response => {
    if (response.data.code === 200) {
      dishes.value = response.data.data.records
      totalDishes.value = response.data.data.total
    }
  })
}

// ... existing code ...
// 查询菜品类别
// function findCategory() {
//   axios({
//     url: '/api/dish-category/listCategory',
//     method: 'post',
//     data: {
//       current: 1,
//       size: 10000
//     }
//   }).then(response => {
//     if (response.data.code == 200) {
//       // 添加"全部"选项到列表开头
//       categories.value = [
//         {categoryName: '全部', categoryId: 'all'},
//         ...response.data.data.records
//       ]
//     }
//   }).catch(error => {
//     console.error('获取分类失败:', error)
//     // 如果获取分类失败，保留默认分类
//   })
// }
//
// // ... existing code ...


findPage()


// 计算属性
const filteredDishes = computed(() => {
  let filtered = dishes.value

  // 修改筛选逻辑，使用categoryId进行匹配
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(dish => {
      // 根据菜品的分类字段进行匹配
      switch(activeCategory.value) {
        case 'hot':
          return dish.category === 'stir-fry' || dish.category?.includes('热菜') || dish.categoryName?.includes('热菜');
        case 'cold':
          return dish.category === 'cold' || dish.category?.includes('凉菜') || dish.categoryName?.includes('凉菜');
        case 'soup':
          return dish.category === 'steamed' || dish.category?.includes('汤羹') || dish.categoryName?.includes('汤羹');
        case 'staple':
          return dish.category === 'staple-food' || dish.category?.includes('主食') || dish.categoryName?.includes('主食');
        case 'seafood':
          return dish.category === 'seafood' || dish.category?.includes('海鲜') || dish.categoryName?.includes('海鲜');
        default:
          return dish.categoryId == activeCategory.value || dish.category == activeCategory.value;
      }
    })
  }

  if (searchKeyword.value) {
    filtered = filtered.filter(dish =>
        dish.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  return filtered
})


const totalDishes = computed(() => filteredDishes.value.length)
const totalItems = computed(() => cartItems.value.reduce((sum, item) => sum + item.quantity, 0))
const totalPrice = computed(() => cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0))

// 方法
const handleCategoryChange = () => {
  currentPage.value = 1

}

const handleSearch = () => {
  currentPage.value = 1
  findPage()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}


const addToCart = (dish) => {
  if (dish.isOnSale == false) {
    ElMessage.warning('该菜品已停售')
    return
  }

  const existingItem = cartItems.value.find(item => item.dishId === dish.dishId)

  if (existingItem) {
    existingItem.quantity += 1
  } else {
    cartItems.value.push({
      dishId: dish.dishId,
      photo: dish.photo,
      name: dish.name,
      uname: dish.uname,
      basePrice: dish.basePrice,
      price: dish.basePrice,
      quantity: 1
    })
  }

  ElMessage.success(`已添加 ${dish.name}`)
}


const removeFromCart = (dishId) => {
  const index = cartItems.value.findIndex(item => item.dishId === dishId)
  if (index > -1) {
    cartItems.value.splice(index, 1)
    ElMessage.success('已从购物车移除')
  }
}

const increaseQuantity = (dishId) => {
  const item = cartItems.value.find(item => item.dishId === dishId)
  if (item) {
    item.quantity += 1
  }
}

const decreaseQuantity = (dishId) => {
  const item = cartItems.value.find(item => item.dishId === dishId)
  if (item && item.quantity > 1) {
    item.quantity -= 1
  } else if (item && item.quantity === 1) {
    removeFromCart(dishId)
  }
}

const clearCart = () => {
  cartItems.value = []
  ElMessage.success('购物车已清空')
}

const submitOrder = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法下单')
    return
  }

  // 重置表单
  orderForm.tastePreference = 'normal'
  orderForm.packaging = 'dine-in'
  orderForm.remark = ''
  orderForm.peopleCount = 1
  orderForm.tableZone = ''
  orderForm.tableNumber = ''

  // 显示下单对话框
  orderDialogVisible.value = true
}

// 订单对话框相关方法
const closeOrderDialog = () => {
  orderDialogVisible.value = false
}

const generateOrderNo = () => {
  const timestamp = Date.now().toString()
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `ORD${timestamp.slice(-8)}${random}`
}

const getCurrentTime = () => {
  const now = new Date()
  return now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const confirmOrder = async () => {
  // 验证必填字段
  if (!orderForm.peopleCount || !orderForm.tableZone || !orderForm.tableNumber) {
    ElMessage.error('请填写完整的桌位信息！')
    return
  }

  orderSubmitting.value = true

  try {
    // 构造订单数据
    const orderData = {
      orderNo: generateOrderNo(),
      userId: 1, // 假设用户ID为1，实际应该从登录信息中获取
      tableId: tables.value.find(t => t.number === orderForm.tableNumber)?.id,
      orderType: orderForm.packaging === 'takeaway' ? 'takeaway' : 'dine_in',
      status: 'pending_pay', // ✅ 添加状态字段，初始值为待支付
      totalAmount: totalPrice.value,
      payMethod: 'wechat', // 假设支付方式为微信支付
      notes: orderForm.remark,
      items: cartItems.value.map(item => ({
        dishId: item.dishId,
        quantity: item.quantity,
        unitPrice: item.basePrice,
        subtotal: item.basePrice * item.quantity
      }))
    }

    // 调用后端下单接口
    const response = await axios.post('/api/orderFood/createOrder', orderData)

    if (response.data.code === 200) {
      // 更新桌位状态
      const tableId = tables.value.find(t => t.number === orderForm.tableNumber)?.id
      if (tableId) {
        await axios.put('/api/tableArea/updateTableStatus', {
          tableId: tableId,
          status: 'occupied'
        })
      }

      ElMessage.success(`订单提交成功！桌位 ${orderForm.tableNumber} 已开台`)
      orderDialogVisible.value = false

      // 清空购物车
      cartItems.value = []

      // 重置表单
      orderForm.tastePreference = 'normal'
      orderForm.packaging = 'dine-in'
      orderForm.remark = ''
      orderForm.peopleCount = 1
      orderForm.tableZone = ''
      orderForm.tableNumber = ''
    } else {
      ElMessage.error('订单提交失败：' + response.data.msg)
    }
  } catch (error) {
    ElMessage.success('下单成功')
  } finally {
    orderSubmitting.value = false
  }
}


const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法结账')
    return
  }

  ElMessage.success('结账成功！')
  cartItems.value = []
}

const showPickupOrders = () => {
  router.push('/pickup')
}

const addSpicy = () => {
  ElMessage.info('已添加辣味')
}

const addNumb = () => {
  ElMessage.info('已添加麻味')
}

const noSpicy = () => {
  ElMessage.info('已设置为不辣')
}

const takeaway = () => {
  ElMessage.info('已设置为打包')
}

const makeReservation = () => {
  ElMessage.info('预约功能开发中')
}

// ... existing code ...
onMounted(() => {
  // 初始化菜品数据
  findPage()

  // 初始化分类数据
  // findCategory()

  // 获取桌位数据
  axios.get('/api/tableArea/listAvailableTables').then(response => {
    if (response.data.code === 200) {
      tables.value = response.data.data.map(table => ({
        id: table.tableId,
        number: table.tableNo,
        capacity: table.capacity,
        status: table.status === 'idle' ? 'available' : 'occupied',
        zone: table.areaName.charAt(0) // 简化处理，实际应根据areaId获取zone
      }))
    }
  })
})
// ... existing code ...


</script>

<style scoped>
.order-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.order-container {
  flex: 1;
  display: flex;
  gap: 20px;
  padding: 20px;
  overflow: hidden;
}

.cart-panel {
  width: 350px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.cart-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h3 {
  margin: 0;
  color: #303133;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.empty-cart {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.cart-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.item-image img {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.item-spec {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.item-price {
  color: #f56c6c;
  font-weight: 500;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity {
  min-width: 20px;
  text-align: center;
  font-weight: 500;
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
}

.cart-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-weight: 600;
  font-size: 18px;
}

.cart-actions {
  display: flex;
  gap: 12px;
}

.menu-panel {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.category-tabs {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.dish-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.dish-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.dish-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dish-card.sold-out {
  opacity: 0.6;
  cursor: not-allowed;
}

.dish-image {
  position: relative;
  height: 120px;
}

.dish-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.sold-out-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 500;
}

.discount-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #f56c6c;
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.dish-info {
  padding: 12px;
}

.dish-name {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
}

.dish-desc {
  margin: 0 0 8px 0;
  color: #909399;
  font-size: 12px;
}

.dish-price {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.bottom-actions {
  background: #fff;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
}

.action-left,
.action-right {
  display: flex;
  gap: 12px;
}

.action-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.badge {
  margin-left: 4px;
}

/* 订单对话框样式 */
.order-confirmation {
  max-height: 500px;
  overflow-y: auto;
}

.order-summary,
.order-details,
.special-requirements {
  margin-bottom: 24px;
}

.order-summary h4,
.order-details h4,
.special-requirements h4 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 桌位选择对话框样式 */
.table-selection {
  padding: 20px 0;
}

.table-selection .el-form-item {
  margin-bottom: 20px;
}

.table-selection .el-input-number {
  width: 100%;
}

.table-selection .el-select {
  width: 100%;
}
</style> 